#include "localinfo.h"
#include "ui_localinfo.h"
#include "systempreset.h"
#include "constants.h"
#include "version.h"

LocalInfo::LocalInfo(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LocalInfo),
    versionDialog(Q_NULLPTR)
{
    bdf = BllDataFlow::getInstance();
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &LocalInfo::retranslateUiSlot);
    connect(bdf, &BllDataFlow::hostVersionSignal, this, &LocalInfo::onHostVersion);
    connect(bdf, &BllDataFlow::updateLocalInfo, this, &LocalInfo::onUpdateLocalInfo);

    ui->setupUi(this);
    onUpdateLocalInfo();
}

LocalInfo::~LocalInfo()
{
    delete ui;
}

static QString mainVersion(const QString &softVersion)
{
    QString version = softVersion;
    version.replace('v', "", Qt::CaseInsensitive);
    QStringList versionList = version.split(".");

    QString mainVersion = "V1.0";
    if (versionList.length() > 1)
    {
        QString v1 = QString("%1").arg(versionList[0].toInt(), 2, 10, QLatin1Char('0'));
        QString v2 = QString("%1").arg(versionList[1].toInt(), 2, 10, QLatin1Char('0'));
        mainVersion = QString("V%1.%2").arg(v1).arg(v2);
    }

    return mainVersion;
}

void LocalInfo::onUpdateLocalInfo()
{
#ifndef AUTO_BUILD
    softVersion = "V1.0";
#else
    softVersion = QString("V%1").arg(GetVersionNumber());
#endif

    ui->lblName->setText(tr(SystemPreset::instance()->getStringData(EnumPresetItem::InstrumentName).toStdString().data()));
    ui->lblModel->setText(SystemPreset::instance()->getStringData(EnumPresetItem::InstrumentType));
    ui->lblSerial->setText(SystemPreset::instance()->getStringData(EnumPresetItem::SerialNumber));
    ui->lblMfr->setText(tr(SystemPreset::instance()->getStringData(EnumPresetItem::CompanyName).toStdString().data()));
    ui->lblAddr->setText(tr(SystemPreset::instance()->getStringData(EnumPresetItem::CompanyAddress).toStdString().data()));
    ui->lblTel->setText(SystemPreset::instance()->getStringData(EnumPresetItem::CompanyTelephone));
    ui->lblVersion->setText(mainVersion(softVersion));

    ui->lblConfig->setText(configNum);
    ui->lblConfig->hide();
    ui->label_33->hide();
}

void LocalInfo::retranslateUiSlot()
{
    ui->retranslateUi(this);
    onUpdateLocalInfo();
}

void LocalInfo::on_btnDetail_clicked()
{
    if (!versionDialog) {
        versionDialog = new VersionDialog();
        versionDialog->setParent(Project::Instance());
    }
    versionDialog->setInfo(softVersion, hostVersion);
    versionDialog->show();
}

void LocalInfo::onHostVersion(const QString &hostVersion)
{
    this->hostVersion = hostVersion;
}

